gpt4 book ai didi

javascript - 调用返回的函数会更干净

转载 作者:行者123 更新时间:2023-12-02 14:17:36 25 4
gpt4 key购买 nike

我有两个返回 Promise 的被调用函数,我想通过使用 catch 语句来捕获错误来使其更清晰。

我认为我正在以正确的方式执行此操作,尽管代码确实以正确的顺序异步调用函数。

这些是我的电话:

// The text is hopefully the email address and the pin number
fb.verifyEmailPin(text).then(function(reply){

// Set the new state to 'get_city'
fb.setState(FB_ID).then(function(result){


}).catch(function(v) {
// Rejection
// If there was an error then prompt the user to enter again
}); // setState

}).catch(function(err){

});// verifyEmailPin

这就是实际的函数 - 对于 setState,我还没有编写 verifyEmailPin 函数的代码,但它在传回解析或拒绝方面遵循与设置状态相同的结构。

/*
* Function : setState
* Purpose : Set the state to what every is send in on the parameter
*/
exports.setState = function(fbid,newstate){

var success = 'Y';
return new Promise((resolve, reject) => {

client.hmset(fbid, { 'state': newstate });

// Check that we have set it ok
client.hmget(fbid,'state',function(err,reply){

if (err || reply != newstate) {
return reject(err);
}

return resolve(success);

});


}).catch(function(v) {

});

}

最佳答案

最后只能使用一个.catch。为了减少缩进,您可以链接 .then。如果您在 then then 函数中执行异步操作,请确保返回一个 Promise,否则后面的 then 将不会等待其完成。对于同步操作(例如 somePromise.then(JSON.parse).then(...)) 不需要 Promise。

这是一个简短的示例:

function promiseTest(x) {
Promise.resolve(x).then(function(a) { // instead of Promise.resolve do something asynchronous, e.g. an ajax call that returns a promise
if (typeof x != "number") throw "NaN";
return a*2;
}).then(function(a) {
console.log(a);
}).catch(function(err) {
console.error("error in promise:", err);
})
}
promiseTest(1); //logs 2 to the console
promiseTest("a"); // shows error message in the console

如果您想并行运行多个异步操作并等待所有操作完成,您可以通过向 Promise.all 提供一组 Promise 来使用它。

Promise.all([doSomethingAsyncAndReturnPromise(), somethingElseAsync()]).then(function results) {
// results[0] contains the result from doSomethingAsyncAndReturnPromise
// results[1] contains the result from somethingElseAsync
});

关于javascript - 调用返回的函数会更干净,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38905351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com