摘要:結(jié)果打印我結(jié)論或問題這里我們基礎(chǔ)實(shí)現(xiàn)了一個(gè)可以用于生產(chǎn)環(huán)境的后續(xù)我們會(huì)接續(xù)完善這個(gè)的特有方法,比如等后續(xù)再介紹用實(shí)現(xiàn)的自動(dòng)執(zhí)行器等附錄參考中文對象入門阮一峰
PHP下的異步嘗試系列
如果你還不太了解PHP下的生成器和協(xié)程,你可以根據(jù)下面目錄翻閱
PHP下的異步嘗試一:初識(shí)生成器
PHP下的異步嘗試二:初識(shí)協(xié)程
PHP下的異步嘗試三:協(xié)程的PHP版thunkify自動(dòng)執(zhí)行器
PHP下的異步嘗試四:PHP版的Promise
PHP下的異步嘗試五:PHP版的Promise的繼續(xù)完善
Promise 實(shí)現(xiàn) 代碼結(jié)構(gòu)│ │ autoload.php │ │ promise1.php │ │ promise2.php │ │ promise3.php │ │ promise4.php │ │ promise5.php │ │ │ └─classes │ Promise1.php │ Promise2.php │ Promise3.php │ Promise4.php │ Promise5.php │ PromiseState.php嘗試一 (Promise基礎(chǔ))
classess/PromiseState.php
final class PromiseState { const PENDING = "pending"; const FULFILLED = "fulfilled"; const REJECTED = "rejected"; }
classess/Promise1.php
// 嘗試一 class Promise1 { private $value; private $reason; private $state; public function __construct(Closure $func = null) { $this->state = PromiseState::PENDING; $func([$this, "resolve"], [$this, "reject"]); } /** * 執(zhí)行回調(diào)方法里的resolve綁定的方法 * @param null $value */ public function resolve($value = null) { // 回調(diào)執(zhí)行resolve傳參的值,賦值給result $this->value = $value; if ($this->state == PromiseState::PENDING) { $this->state = PromiseState::FULFILLED; } } public function reject($reason = null) { // 回調(diào)執(zhí)行resolve傳參的值,賦值給result $this->reason = $reason; if ($this->state == PromiseState::PENDING) { $this->state = PromiseState::REJECTED; } } public function getState() { return $this->state; } public function getValue() { return $this->value; } public function getReason() { return $this->reason; } }
promise1.php
require "autoload.php"; $promise = new Promise1(function($resolve, $reject) { $resolve("打印我"); }); var_dump($promise->getState()); var_dump($promise->getValue());結(jié)果:
string(9) "fulfilled" string(9) "打印我"結(jié)論或問題:
我們在這里建構(gòu)了最基礎(chǔ)的Promise模型嘗試二 (增加鏈?zhǔn)絫hen)
classess/Promise2.php
state = PromiseState::PENDING; $func([$this, "resolve"], [$this, "reject"]); } public function then(Closure $onFulfilled = null, Closure $onRejected = null) { // 如果狀態(tài)是fulfilled,直接回調(diào)執(zhí)行并傳參value if ($this->state == PromiseState::FULFILLED) { $onFulfilled($this->value); } // 如果狀態(tài)是rejected,直接回調(diào)執(zhí)行并傳參reason if ($this->state == PromiseState::REJECTED) { $onRejected($this->reason); } // 返回對象自身,實(shí)現(xiàn)鏈?zhǔn)秸{(diào)用 return $this; } /** * 執(zhí)行回調(diào)方法里的resolve綁定的方法 * 本狀態(tài)只能從pending->fulfilled * @param null $value */ public function resolve($value = null) { if ($this->state == PromiseState::PENDING) { $this->state = PromiseState::FULFILLED; $this->value = $value; } } /** * 執(zhí)行回調(diào)方法里的rejected綁定的方法 * 本狀態(tài)只能從pending->rejected * @param null $reason */ public function reject($reason = null) { if ($this->state == PromiseState::PENDING) { $this->state = PromiseState::REJECTED; $this->reason = $reason; } } public function getState() { return $this->state; } public function getValue() { return $this->value; } public function getReason() { return $this->reason; } }
promise2.php
then(function ($value) { var_dump($value); }, function ($reason) { var_dump($reason); })->then(function ($value) { var_dump($value); }, function ($reason) { var_dump($reason); });結(jié)果:
string(9) "打印我" string(9) "打印我"結(jié)論或問題:
我們實(shí)現(xiàn)了鏈?zhǔn)絫hen方法 如果我們的構(gòu)造里的回調(diào)是異步執(zhí)行的話,那么狀態(tài)在沒有變成fulfilled之前,我們then里的回調(diào)方法就永遠(yuǎn)沒法執(zhí)行嘗試三(真正的鏈?zhǔn)絫hen)
classess/Promise3.php
// 解決思路:我們肯定要把then傳入的回調(diào),放到Promise構(gòu)造里回調(diào)代碼執(zhí)行完后resolve調(diào)用后改變了state狀態(tài)后再調(diào)用,所以我們必須存儲(chǔ)到一個(gè)地方并方便后續(xù)調(diào)用 // 我們需要改造then、resolve和reject方法 class Promise3 { private $value; private $reason; private $state; private $fulfilledCallbacks = []; private $rejectedCallbacks = []; public function __construct(Closure $func = null) { $this->state = PromiseState::PENDING; $func([$this, "resolve"], [$this, "reject"]); } public function then(Closure $onFulfilled = null, Closure $onRejected = null) { // 如果是異步回調(diào),狀態(tài)未變化之前,then的回調(diào)方法壓入相應(yīng)的數(shù)組方便后續(xù)調(diào)用 if ($this->state == PromiseState::PENDING) { $this->fulfilledCallbacks[] = static function() use ($onFulfilled, $value){ $onFulfilled($this->value); }; $this->rejectedCallbacks[] = static function() use ($onRejected, $reason){ $onRejected($this->reason); }; } // 如果狀態(tài)是fulfilled,直接回調(diào)執(zhí)行并傳參value if ($this->state == PromiseState::FULFILLED) { $onFulfilled($this->value); } // 如果狀態(tài)是rejected,直接回調(diào)執(zhí)行并傳參reason if ($this->state == PromiseState::REJECTED) { $onRejected($this->reason); } // 返回對象自身,實(shí)現(xiàn)鏈?zhǔn)秸{(diào)用 return $this; } /** * 執(zhí)行回調(diào)方法里的resolve綁定的方法 * 本狀態(tài)只能從pending->fulfilled * @param null $value */ public function resolve($value = null) { if ($this->state == PromiseState::PENDING) { $this->state = PromiseState::FULFILLED; $this->value = $value; array_walk($this->fulfilledCallbacks, function ($callback) { $callback(); }); } } /** * 執(zhí)行回調(diào)方法里的rejected綁定的方法 * 本狀態(tài)只能從pending->rejected * @param null $reason */ public function reject($reason = null) { if ($this->state == PromiseState::PENDING) { $this->state = PromiseState::REJECTED; $this->reason = $reason; } } public function getState() { return $this->state; } public function getValue() { return $this->value; } public function getReason() { return $this->reason; } }
promise3.php
require "autoload.php"; $promise = new Promise3(function($resolve, $reject) { $resolve("打印我"); }); $promise->then(function ($value) { var_dump($value); }, function ($reason) { var_dump($reason); })->then(function ($value) { var_dump($value); }, function ($reason) { var_dump($reason); });結(jié)果:
string(9) "打印我" string(9) "打印我"結(jié)論或問題:
我們這次基本實(shí)現(xiàn)了真正的鏈?zhǔn)絫hen方法 不過在Promise/A+里規(guī)范,要求then返回每次都要求是一個(gè)新的Promise對象 then方法成功執(zhí)行,相當(dāng)于返回一個(gè)實(shí)例一個(gè)Promise回調(diào)里執(zhí)行resolve方法,resolve值為then里return的值 then方法執(zhí)行失敗或出錯(cuò),相當(dāng)于返回一個(gè)實(shí)例一個(gè)Promise回調(diào)里執(zhí)行rejected方法,rejected值為then里return的值嘗試四(then返回pormise對象, 并傳遞上一次的結(jié)果給下一個(gè)Promise對象)
classess/Promise4.php
class Promise4 { private $value; private $reason; private $state; private $fulfilledCallbacks = []; private $rejectedCallbacks = []; public function __construct(Closure $func = null) { $this->state = PromiseState::PENDING; $func([$this, "resolve"], [$this, "reject"]); } public function then(Closure $onFulfilled = null, Closure $onRejected = null) { $thenPromise = new Promise4(function ($reslove, $reject) use (&$thenPromise, $onFulfilled, $onRejected) { //$this 代表的當(dāng)前的Promise對象,不要混淆了 // 如果是異步回調(diào),狀態(tài)未變化之前,then的回調(diào)方法壓入相應(yīng)的數(shù)組方便后續(xù)調(diào)用 if ($this->state == PromiseState::PENDING) { $this->fulfilledCallbacks[] = static function() use ($thenPromise, $onFulfilled, $reslove, $reject){ $value = $onFulfilled($this->value); $this->resolvePromise($thenPromise, $value, $reslove, $reject); }; $this->rejectedCallbacks[] = static function() use ($thenPromise, $onRejected, $reslove, $reject){ $reason = $onRejected($this->reason); $this->resolvePromise($thenPromise, $reason, $reslove, $reject); }; } // 如果狀態(tài)是fulfilled,直接回調(diào)執(zhí)行并傳參value if ($this->state == PromiseState::FULFILLED) { $value = $onFulfilled($this->value); $this->resolvePromise($thenPromise, $value, $reslove, $reject); } // 如果狀態(tài)是rejected,直接回調(diào)執(zhí)行并傳參reason if ($this->state == PromiseState::REJECTED) { $reason = $onRejected($this->reason); $this->resolvePromise($thenPromise, $reason, $reslove, $reject); } }); // 返回對象自身,實(shí)現(xiàn)鏈?zhǔn)秸{(diào)用 return $thenPromise; } /** * 解決Pormise鏈?zhǔn)絫hen傳遞 * 可參考 [Promises/A+]2.3 [https://promisesaplus.com/#the-promise-resolution-procedure] * @param $thenPromise * @param $x $x為thenable對象 * @param $resolve * @param $reject */ private function resolvePromise($thenPromise, $x, $resolve, $reject) { $called = false; if ($thenPromise === $x) { return $reject(new Exception("循環(huán)引用")); } if ( is_object($x) && method_exists($x, "then")) { $resolveCb = function ($value) use($thenPromise, $resolve, $reject, $called) { if ($called) return ; $called = true; // 成功值y有可能還是promise或者是具有then方法等,再次resolvePromise,直到成功值為基本類型或者非thenable $this->resolvePromise($thenPromise, $value, $resolve, $reject); }; $rejectCb = function($reason) use($thenPromise, $resolve, $reject, $called) { if ($called) return ; $called = true; $reject($reason); }; call_user_func_array([$x, "then"], [$resolveCb, $rejectCb]); } else { if ($called) return ; $called = true; $resolve($x); } } /** * 執(zhí)行回調(diào)方法里的resolve綁定的方法 * 本狀態(tài)只能從pending->fulfilled * @param null $value */ public function resolve($value = null) { if ($this->state == PromiseState::PENDING) { $this->state = PromiseState::FULFILLED; $this->value = $value; array_walk($this->fulfilledCallbacks, function ($callback) { $callback(); }); } } /** * 執(zhí)行回調(diào)方法里的rejected綁定的方法 * 本狀態(tài)只能從pending->rejected * @param null $reason */ public function reject($reason = null) { if ($this->state == PromiseState::PENDING) { $this->state = PromiseState::REJECTED; $this->reason = $reason; } } public function getState() { return $this->state; } public function getValue() { return $this->value; } public function getReason() { return $this->reason; } }
promise4.php
require "autoload.php"; $promise1 = new Promise4(function($resolve, $reject) { $resolve("打印我"); }); $promise2 = $promise1->then(function ($value) { var_dump($value); return "promise2"; }, function ($reason) { var_dump($reason); }); $promise3 = $promise2->then(function ($value) { var_dump($value); return new Promise4(function($resolve, $reject) { $resolve("promise3"); }); }, function ($reason) { var_dump($reason); }); $promise4 = $promise3->then(function ($value) { var_dump($value); return "promise4"; }, function ($reason) { var_dump($reason); }); var_dump($promise4);結(jié)果:
string(9) "打印我" string(8) "promise2" string(8) "promise3" object(Promise4)#15 (5) { ["value":"Promise4":private]=> string(8) "promise4" ["reason":"Promise4":private]=> NULL ["state":"Promise4":private]=> string(9) "fulfilled" ["fulfilledCallbacks":"Promise4":private]=> array(0) { } ["rejectedCallbacks":"Promise4":private]=> array(0) { } }結(jié)論或問題:
一個(gè)基本的Pormise,不過我們上面都是基于成功fulfilled狀態(tài)的實(shí)現(xiàn) 下面我們來增加錯(cuò)誤捕獲嘗試五(錯(cuò)誤捕獲)
classess/Promise5.php
class Promise5 { private $value; private $reason; private $state; private $fulfilledCallbacks = []; private $rejectedCallbacks = []; public function __construct(Closure $func = null) { $this->state = PromiseState::PENDING; $func([$this, "resolve"], [$this, "reject"]); } public function then(Closure $onFulfilled = null, Closure $onRejected = null) { // 此處作用是兼容then方法的以下四種參數(shù)變化,catchError就是第二種情況 // 1. then($onFulfilled, null) // 2. then(null, $onRejected) // 3. then(null, null) // 4. then($onFulfilled, $onRejected) $onFulfilled = is_callable($onFulfilled) ? $onFulfilled : function ($value) {return $value;}; $onRejected = is_callable($onRejected) ? $onRejected : function ($reason) {throw $reason;}; $thenPromise = new Promise5(function ($reslove, $reject) use (&$thenPromise, $onFulfilled, $onRejected) { //$this 代表的當(dāng)前的Promise對象,不要混淆了 // 如果是異步回調(diào),狀態(tài)未變化之前,then的回調(diào)方法壓入相應(yīng)的數(shù)組方便后續(xù)調(diào)用 if ($this->state == PromiseState::PENDING) { $this->fulfilledCallbacks[] = static function() use ($thenPromise, $onFulfilled, $reslove, $reject){ try { $value = $onFulfilled($this->value); $this->resolvePromise($thenPromise, $value, $reslove, $reject); } catch (Exception $e) { $reject($e); } }; $this->rejectedCallbacks[] = static function() use ($thenPromise, $onRejected, $reslove, $reject){ try { $reason = $onRejected($this->reason); $this->resolvePromise($thenPromise, $reason, $reslove, $reject); } catch (Exception $e) { $reject($e); } }; } // 如果狀態(tài)是fulfilled,直接回調(diào)執(zhí)行并傳參value if ($this->state == PromiseState::FULFILLED) { try { $value = $onFulfilled($this->value); $this->resolvePromise($thenPromise, $value, $reslove, $reject); } catch (Exception $e) { $reject($e); } } // 如果狀態(tài)是rejected,直接回調(diào)執(zhí)行并傳參reason if ($this->state == PromiseState::REJECTED) { try { $reason = $onRejected($this->reason); $this->resolvePromise($thenPromise, $reason, $reslove, $reject); } catch (Exception $e) { $reject($e); } } }); // 返回對象自身,實(shí)現(xiàn)鏈?zhǔn)秸{(diào)用 return $thenPromise; } public function catchError($onRejected) { return $this->then(null, $onRejected); } /** * 解決Pormise鏈?zhǔn)絫hen傳遞 * 可參考 [Promises/A+]2.3 [https://promisesaplus.com/#the-promise-resolution-procedure] * @param $thenPromise * @param $x $x為thenable對象 * @param $resolve * @param $reject */ private function resolvePromise($thenPromise, $x, $resolve, $reject) { $called = false; if ($thenPromise === $x) { return $reject(new Exception("循環(huán)引用")); } if ( is_object($x) && method_exists($x, "then")) { try { $resolveCb = function ($value) use ($thenPromise, $resolve, $reject, $called) { if ($called) return; $called = true; // 成功值y有可能還是promise或者是具有then方法等,再次resolvePromise,直到成功值為基本類型或者非thenable $this->resolvePromise($thenPromise, $value, $resolve, $reject); }; $rejectCb = function ($reason) use ($thenPromise, $resolve, $reject, $called) { if ($called) return; $called = true; $reject($reason); }; call_user_func_array([$x, "then"], [$resolveCb, $rejectCb]); } catch (Exception $e) { if ($called) return ; $called = true; $reject($e); } } else { if ($called) return ; $called = true; $resolve($x); } } /** * 執(zhí)行回調(diào)方法里的resolve綁定的方法 * 本狀態(tài)只能從pending->fulfilled * @param null $value */ public function resolve($value = null) { if ($this->state == PromiseState::PENDING) { $this->state = PromiseState::FULFILLED; $this->value = $value; array_walk($this->fulfilledCallbacks, function ($callback) { $callback(); //因?yàn)榛卣{(diào)本身攜帶了作用于,所以直接調(diào)用,無法參數(shù) }); } } /** * 執(zhí)行回調(diào)方法里的rejected綁定的方法 * 本狀態(tài)只能從pending->rejected * @param null $reason */ public function reject($reason = null) { if ($this->state == PromiseState::PENDING) { $this->state = PromiseState::REJECTED; $this->reason = $reason; array_walk($this->rejectedCallbacks, function ($callback) { $callback(); //因?yàn)榛卣{(diào)本身攜帶了作用于,所以直接調(diào)用,無法參數(shù) }); } } public function getState() { return $this->state; } public function getValue() { return $this->value; } public function getReason() { return $this->reason; } }
promise5.php
require "autoload.php"; $promise1 = new Promise5(function($resolve, $reject) { $resolve("打印我"); }); $promise2 = $promise1->then(function ($value) { var_dump($value); throw new Exception("promise2 error"); return "promise2"; }, function ($reason) { var_dump($reason->getMessage()); return "promise3 error return"; }); //我們可以簡寫then方法,只傳入$onFulfilled方法,然后錯(cuò)誤會(huì)自己冒泡方式到下一個(gè)catchError或then里處理。 //$promise3 = $promise2->then(function ($value) { // var_dump($value); // return new Promise5(function($resolve, $reject) { // $resolve("promise3"); // }); //})->catchError(function ($reason) { // var_dump($reason->getMessage()); // return "promise3 error return"; //}); $promise3 = $promise2->then(function ($value) { var_dump($value); return new Promise5(function($resolve, $reject) { $resolve("promise3"); }); }, function ($reason) { var_dump($reason->getMessage()); return "promise3 error return"; }); $promise4 = $promise3->then(function ($value) { var_dump($value); return "promise4"; }, function ($reason) { echo $reason->getMessage(); }); var_dump($promise4);結(jié)果:
string(9) "打印我" string(14) "promise2 error" string(21) "promise3 error return" object(Promise4)#10 (5) { ["value":"Promise4":private]=> string(8) "promise4" ["reason":"Promise4":private]=> NULL ["state":"Promise4":private]=> string(9) "fulfilled" ["fulfilledCallbacks":"Promise4":private]=> array(0) { } ["rejectedCallbacks":"Promise4":private]=> array(0) { } }結(jié)論或問題:
這里我們基礎(chǔ)實(shí)現(xiàn)了一個(gè)可以用于生產(chǎn)環(huán)境的Promise 后續(xù)我們會(huì)接續(xù)完善這個(gè)Promise的特有方法,比如:finally, all, race, resolve, reject等 后續(xù)再介紹用Promise實(shí)現(xiàn)的自動(dòng)執(zhí)行器等附錄參考
Promises/A+
Promises/A+ 中文
Promise 對象 - ECMAScript 6 入門 阮一峰
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/29463.html
摘要:如果僅依靠程序自動(dòng)交出控制的話,那么一些惡意程序?qū)?huì)很容易占用全部時(shí)間而不與其他任務(wù)共享。多個(gè)操作可以在重疊的時(shí)間段內(nèi)進(jìn)行。 PHP下的異步嘗試系列 如果你還不太了解PHP下的生成器,你可以根據(jù)下面目錄翻閱 PHP下的異步嘗試一:初識(shí)生成器 PHP下的異步嘗試二:初識(shí)協(xié)程 PHP下的異步嘗試三:協(xié)程的PHP版thunkify自動(dòng)執(zhí)行器 PHP下的異步嘗試四:PHP版的Promise ...
摘要:函數(shù)并不是生成器協(xié)程函數(shù)自動(dòng)執(zhí)行的唯一方案。因?yàn)樽詣?dòng)執(zhí)行的關(guān)鍵是,必須有一種機(jī)制,自動(dòng)控制生成器協(xié)程函數(shù)的流程,接收和交還程序的執(zhí)行權(quán)。回調(diào)函數(shù)可以做到這一點(diǎn),對象也可以做到這一點(diǎn)。本系列的下一篇,將介紹基于的實(shí)現(xiàn)的自動(dòng)執(zhí)行器。 PHP下的異步嘗試系列 如果你還不太了解PHP下的生成器和協(xié)程,你可以根據(jù)下面目錄翻閱 PHP下的異步嘗試一:初識(shí)生成器 PHP下的異步嘗試二:初識(shí)協(xié)程 P...
摘要:下的異步嘗試系列下的異步嘗試一初識(shí)生成器下的異步嘗試二初識(shí)協(xié)程下的異步嘗試三協(xié)程的版自動(dòng)執(zhí)行器下的異步嘗試四版的下的異步嘗試五版的的繼續(xù)完善生成器類獲取迭代器當(dāng)前值獲取迭代器當(dāng)前值返回當(dāng)前產(chǎn)生的鍵生成器從上一次處繼續(xù)執(zhí)行重置迭代器向生成器中 PHP下的異步嘗試系列 PHP下的異步嘗試一:初識(shí)生成器 PHP下的異步嘗試二:初識(shí)協(xié)程 PHP下的異步嘗試三:協(xié)程的PHP版thunkify自...
摘要:四異步編程解決方案模式模式一定程度上緩解了嵌套回調(diào)的問題,只會(huì)處在未完成完成態(tài)失敗態(tài)中的一種,只會(huì)從未完成轉(zhuǎn)化為完成態(tài)或者失敗態(tài),不能逆轉(zhuǎn)。 一、從一個(gè)簡單的案例開始 fs.readdir(path.join(__dirname, ./index.js), (err, files) => { files.foreach((filename, index) => { ...
摘要:一涉及技術(shù)二簡介官方文檔三種狀態(tài)進(jìn)行中已完成,又稱已失敗只有異步操作的結(jié)果,可以決定當(dāng)前是哪一種狀態(tài),任何其他操作都無法改變這個(gè)狀態(tài)。 一、涉及技術(shù) jquery、vue、php 二、Promise簡介 MDN官方文檔:Promise 三種狀態(tài): Pending(進(jìn)行中) Resolved(已完成,又稱 Fulfilled) Rejected(已失敗) 只有異步操作的結(jié)果,可以決定...
閱讀 790·2023-04-25 17:33
閱讀 3645·2021-07-29 14:49
閱讀 2491·2019-08-30 15:53
閱讀 3445·2019-08-29 16:27
閱讀 2013·2019-08-29 16:11
閱讀 1041·2019-08-29 14:17
閱讀 2451·2019-08-29 13:47
閱讀 2028·2019-08-29 13:28