[英]Promisifying an synchorous function
所以,我有這樣的代碼。
getSomethingAsync(something)
.then(doSomethingAsync)
.then(function(d) {
_d = doSomethingSync(d);
return doSomethingAsyncNext(_d);
})
.then(function(val) {
//All done
})
.catch(err_handler);
我想把它變成類似的東西。
getSomethingAsync(something)
.then(doSomethingAsync)
.then(doSomethingSync)
.then(doSomethingAsyncNext)
.then(function(val) {
//All done
})
.catch(err_handler);
我應該只更改doSomethingSync嗎?
function(data) {
// do a lot of things with data, throw errors for invalid data
return changed_data;
}
至:
function(data) {
// do a lot of things with data, throw errors for invalid data
return new Promise(function(resolve,reject){
resolve(changed_data);
});
}
要么:
function(data) {
return new Promise(function(resolve,reject){
// do a lot of things with data, reject for invalid data
resolve(changed_data);
});
}
我應該改變doSomethingSync這是...
您不必全部更改。 如果回調的返回值不是 promise,則將其直接用於解析.then
返回的promise。 的.then
回調沒有返回的承諾。
你可以寫
return Promise.resolve(changed_data);
但是同樣,沒有必要。 return changed_data;
將同樣有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.