node.js - 在函数返回值之前等待 promise 解决

标签 node.js

<分区>

我正在尝试执行以下代码:

exports.myFunction = function(){
    myPromise.doThis().then(ret => {
     return ret;
    });
}

调用此函数时,它返回 undefined。我如何让函数等待 promise 解决然后返回。

最佳答案

由于是异步的,因此无法保证知道 promise 何时会得到解决。它可能需要等待一段时间(取决于您在做什么)。

在 promise 之后继续执行的典型方法是通过链接执行或使用回调函数。

作为回调

您的示例代码(对我而言)建议使用回调。

exports.myFunction = function(callback){
    myPromise.doThis().then(ret => {
        callback(ret);
    });
}

然后使用看起来类似于:

var myFunction = require('pathToFile').myFunction;

myFunction(function(ret){
    //Do what's required with ret here
});

编辑:

正如@torazaburo 提到的,该函数可以浓缩为:

exports.myFunction = function(callback){
    myPromise.doThis().then(callback);
} 

作为 promise

exports.myFunction = function(){
    //Returnes a promise
    return myPromise.doThis();
}

然后使用看起来类似于:

var myFunction = require('pathToFile').myFunction;

myFunction().then(function(ret){
    //Do what's required with ret here
});

关于node.js - 在函数返回值之前等待 promise 解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37200460/

相关文章:

javascript - Mongoose /Mongodb : Index Already Exists With Different Options

javascript - 通过键查找获取值并替换为嵌套 json 对象中的第二个 json 值

javascript - Passportjs 获取身份验证错误消息

node.js - socket.io 错误 - Web 套接字连接在建立连接之前关闭

node.js - Sequelize - 错误许多具有相同名称的关系 foreignKey - MyModel.hasMany 调用的东西不是 Sequelize.Model 的子类

node.js - Google reCAPTCHA无法在Electron BrowserWindow中解决

javascript - 在函数外部声明变量

node.js - Bot 框架异步问题

node.js - 指定的文件全局模​​式与任何文件都不匹配

javascript - 将异步/等待 block 中的部分代码提取到单独的函数中