如何将参数传递给Promise函数

这似乎是一个愚蠢的问题,但是我是这个话题的新手。我正在致力于关于节点js的承诺。我想将参数传递给Promise函数。但是我不知道。

someModule.someFunction.then(username, password,function(uid) {

/*stuff */

}

而功能类似于

var someFunction = new Promise(username, password, function(resolve, reject) {

/*stuff using username, password*/

if ( /* everything turned out fine */ ) {

resolve("Stuff worked!");

} else {

reject(Error("It broke"));

}

});

回答:

将Promise包裹在一个函数中,否则它将立即开始工作。另外,您可以将参数传递给函数:

var someFunction = function(username, password) {

return new Promise(function(resolve, reject) {

/*stuff using username, password*/

if ( /* everything turned out fine */ ) {

resolve("Stuff worked!");

} else {

reject(Error("It broke"));

}

});

}

然后,使用它:

someModule.someFunction(username, password).then(function(uid) {

/* stuff */

})

const someFunction = (username, password) => {

return new Promise((resolve, reject) => {

/*stuff using username, password*/

if ( /* everything turned out fine */ ) {

resolve("Stuff worked!");

} else {

reject(Error("It broke"));

}

});

};

用:

someModule.someFunction(username, password).then(uid => {

/* stuff */

});

以上是 如何将参数传递给Promise函数 的全部内容, 来源链接: utcz.com/qa/435301.html

回到顶部