2017-07-01 71 views
1

我完全重寫我的問題,甚至進一步煮沸它。nodejs承諾只是不等待

爲什麼,在下面的代碼,確實x()等同於undefined代替success其通過console.log('success');

最後一行結束在控制檯執行記錄到控制檯;那麼將觸發.then()回叫。

我該如何做到這一點,x()在最後一行開始執行之前返回'成功'值。

即使yF()評估爲undefined。但是,然後()回顯th y: success

const promise = require('promise'); 
const requestify = require('requestify'); 


function x() { 
    requestify.get('https://<redacted>/') 
     .then(function (d) { 
      console.log('success', d.code); 
      return 'success'; 
     }) 
     .fail(function (f) { 
      console.log('fail', f.code); 
      return 'fail'; 
     }); 
    ; 
} 


var yF = function() { 
    yP .then(function (th) { console.log("th", th); return th; }) 
     .catch(function (fl) { console.log("fl", fl); return fl; }); 
} 


var yP = new Promise(
    function (resolve, reject) { 
     if (1 == 1) { 
      resolve("y: success"); 
     } else { 
      reject(new Error("y: fail")); 
     } 
    } 
); 




console.log("hello", x()); 
console.log("world", yF()); 
+0

請進一步解釋。你是說在requestify.get的then子句中的代碼在請求完成之前被觸發? – user93

+0

您是否在完成所有操作之後在內部完成請求 – user93

回答

0

函數x不返回值。此示例可能有所幫助:

> function foo() { console.log('hi from foo'); } 
undefined 
> console.log('calling foo', foo()); 
hi from foo 
calling foo undefined 

您需要在函數中返回promise。功能x可以改變這樣的:

function x() { 
    return requestify.get('https://<redacted>/') 
     .then(function (d) { 
      console.log('success', d.code); 
      return 'success'; 
     }) 
     .fail(function (f) { 
      console.log('fail', f.code); 
      return 'fail'; 
     }); 
} 

現在,您可以撥打xthen

x().then(result => assert(result === 'success')); 
+0

也許不適合您,但是對於我來說,console.log(「hello ,,, x()。then()解析爲'hello {state:'pending '}'。謝謝提醒我可以返回'requestify()',這個函數只能打開一個燈泡 – user5903880

0

兩種方法:

1)x()〜我會打電話,傳遞變量向前

2)yP()〜消費承諾

const promise = require('promise'); 
const requestify = require('requestify'); 

var f = ""; 


function yP() { 
    return new Promise(function (resolve, reject) { 
     requestify.get('https://<redacted>') 
      .then(function (da) { 
       var fpt = "success(yP):" + da.code.toString(); 
       console.log('success-yP', fpt); 
       resolve(fpt); 
      }) 
      .catch(function (ca) { 
       var fpc = "fail(yP):" + ca.code.toString(); 
       console.log('fail-yP', fpc); 
       reject(fpc); 
      }); 
    }); 
} 


function x() { 
    requestify.get('https://<redacted>/') 
     .then(function (da) { 
      f = "success(x):" + da.code.toString(); 
      console.log('success-x', f); 
      consumef(); 
     }) 
     .catch(function (ca) { 
      f = "fail(x):" + ca.code.toString(); 
      console.log('fail-x', ca); 
      consumef(); 
     }); 
    ; 
} 


function consumef() { 
    console.log("hello", f); 

} 



x(); 
yP() 
    .then(function (fyPt) { console.log('yP().then', fyPt); }) 
    .catch(function (fyPc) { console.log('yP().catch', fyPc); }); 

調試器偵聽[:]:5858

成功-YP成功(YP):200

YP(),然後成功(YP):200次

成功-x成功(X):200次

你好成功(X):200

+0

再次閱讀我的答案。您不需要在'yP'函數中創建額外的承諾,只需返回值。 –