我如何 return 来自函数的 Promise 的值?

How do I return the value of a Promise from a function?

我知道您可以像下面的代码一样在 .then 方法中访问 Promise 的值:

const Promise = require("bluebird");
const fs = Promise.promisifyAll(require('fs'));
const mergeValues = require('./helper').mergeValues;


fs.readFileAsync('./index.html', {encoding: "utf8"})
    .then((data) => {
        return mergeValues(values, data); //async function that returns a promise
    })
    .then((data) => {
        console.log(data);
    });

在上面的示例中,我从文件中读取数据,将数据与一些值合并,然后将数据记录到控制台。

但是如何从函数返回值,就像您通常在同步函数中那样?如果我按照,我认为代码应该是这样的:

function getView(template, values) {
    let file = fs.readFileAsync('./' + template, {encoding: "utf8"});
    let modifiedFile = file.then((data) => {
            return mergeValues(values, data);
        });
    return modifiedFile.then((data) => {
        return modifiedFile.value();
    });
}
console.log(getView('index.html', null));

但由于某种原因,它不起作用。我在控制台中得到的只是 Promise 对象本身,而不是值。当我在 modifiedFile 上添加 .isFulfilled 方法时,它输出到 true。所以我不确定我做错了什么。

承诺不是那样的。它们本质上是 异步的,因此您不能像使用同步代码那样与它们交互。

这意味着您必须使用then方法来获取值:

function getView(template, values) {
    let file = fs.readFileAsync('./' + template, {encoding: "utf8"});
    let modifiedFile = file.then((data) => {
            return mergeValues(values, data);
        });
    return modifiedFile.then((data) => {
        return modifiedFile.value();
    });
}
// This won't work
// console.log(getView('index.html', null)); 

// instead:
getView('index.html', null).then(function (view) {
    console.log(view);
});

So I’m not sure what I’m doing incorrectly.

其实你并没有做错什么。您不能像函数中的正常 return 值那样使用承诺。期间.