2017-01-30 254 views
0

我知道你可以訪問Promise的價值.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); 
    }); 

在上面的例子中,我從文件中讀取,具有一定的價值合併數據,然後記錄該數據到控制檯。

但是關於從函數返回值,怎麼樣,你通常會在同步功能?如果我按照this comment on synchronous inspection,我覺得代碼應該是這樣的:

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對象本身,而不是價值。當我加入.isFulfilled方法上modifiedFile,輸出到true。所以我不確定我做錯了什麼。

+0

你可以永遠從異步返回一個值。永遠。典型的答案:我如何返回從一個異步調用的響應(http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)。 – Amadan

+0

一旦你提交了一個異步調用,那麼取決於該操作的任何結果的所有內容都是異步的。也就是說,如果你在你的函數中使用了Promise,並且你需要從中得到一些東西,那麼返回一個promise。你不能在周圍等待。 – tadman

回答

1

承諾不是這樣的。它們本質上是異步的異步,所以你不能以與你使用同步代碼相同的方式與它們進行交互。

這意味着你必須使用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); 
}); 

所以我不知道我在做什麼錯誤。

你什麼都沒有做正確,其實。你不能像使用函數的正常返回值那樣使用promise。期。

+0

感謝您的解釋! –