2017-08-25 15 views
0

約束を解決したら、範囲外の値を渡すことができません。 こちらのコードを確認してください。範囲外の約束で解決された値にアクセスする方法

var FullName; 
 
async.series([ 
 
    function(callback) { 
 
    var name = element(by.css('.xyz')).getText().then(function(text) { 
 
     console.log("print name" + text); 
 
     FullName = text; 
 
     console.log("Able to print successfully" + FullName); 
 
    }); 
 
    console.log("Unable to print the name outside" + FullName); 
 
    callback(); 
 
    }, 
 
    function(callback) { 
 
    //I want to retrieve the FullName value to this function. 
 
    //but unable to bring the value to this function 
 
    console.log("Unable to print the name on the second function too" + FullName) 
 
    callback(); 
 
    } 
 

 
], function(err) { 
 
    done(); 
 
})

+0

と同等です:[どのように私は非同期呼び出しからの応答を返さない](https://stackoverflow.com/questions/14220321/how-do-i非同期呼び出しからの応答)。 – jfriend00

+3

'async'ライブラリと約束を混ぜるのは、一般的に混乱です。あなたの基礎となる操作が既に(ここにあるように見える)約束を使用している場合は、非同期ライブラリではなく、フロー制御用の約束を使用してください。 – jfriend00

答えて

0

私はあなたがこの

var FullName; 
async.series([ 
    function(callback) { 
    var name = element(by.css('.xyz')).getText().then(function(text) { 
     console.log("print name" + text); 
     FullName = text; 
     console.log("Able to print successfully" + FullName); 
     callback(); // callback once all asynchronous ops are done 
    }); 
    }, 
    function(callback) { 
    console.log("Now able to print the name on the second function " + FullName) 
    callback(); 
    } 

], function(err) { 
    done(); 
}) 

またはとしてそれを書き換えるという問題

var FullName; 
async.series([ 
    function(callback) { 
    var name = element(by.css('.xyz')).getText().then(function(text) { 
     console.log("print name" + text); 
     FullName = text; 
     console.log("Able to print successfully" + FullName); 
    }); 
    // here, the .then callback hasn't been invoked yet, so FullName is not yet changed 
    console.log("Unable to print the name outside" + FullName); 
    // and, you're calling callback() before the .then callback is invoked, so, in the next code, FullName is not changed either 
    callback(); 
    }, 

を説明するために、コードの最初の部分にコメントを追加しました、async.jsを使わないで、Promises + async.jsは決してリアルではないのでLY良い組み合わせは、とにかく、あなたのコードは、可能性のある重複

element(by.css('.xyz')).getText() 
.then(function(FullName) { 
    // do wahtever you need to with FullName in here, note it's NOT global 
}); 
+0

グローバルな 'FullName'変数を避けるために書き直してください。古いコールバックスタイルであっても、値は関数呼び出しによって渡されます:-) – Bergi

+0

私はこれを約束の唯一の例で行いました –

関連する問題