2017-02-14 8 views
1

解決済みの値を変更する約束チェーン内で使用できる関数を作成しようとしています。jquery約束チェーンの解決された値を変更する方法

以下では、関数getAndChangeValue()を使用して解決された引数を "Hello"から "Bye"に変更します。助けてください!私はそれの周りに私の頭を得るように見えることはできません。 :-)

https://plnkr.co/edit/RL1XLeQdkZ8jd8IezMYr?p=preview

getAndChangeValue().then(function(arg) { 
    console.log(arg) // I want this to say "Bye" 
}); 


function getAndChangeValue() { 

    var promise = getValue() 
    promise.then(function(arg) { 
     console.log('arg:', arg) // says "Hello" 

     // do something here to change it to "Bye" 
    }) 
    return promise 
} 

function getValue() { // returns promise 

    return $.ajax({ 
     url: "myFile.txt", 
     type: 'get' 

    }); 
} 
+0

var firstPromise = new Promise(function (resolve, reject) { return resolve('FIRST-VALUE'); }) .then(function (response) { console.log(response); // FIRST-VALUE var secondPromise = new Promise(function (resolve) { resolve('SECOND-VALUE'); }); // Here we are changing the return value from 'SECOND-VALUE' to 'FIRST-VALUE' return secondPromise.return(response); }) .then(function (response) { console.log(response); // FIRST-VALUE }) 
これは非常に奇妙な要件です。返されたものを無視する場合、なぜAJAXリクエストを作成するのが嫌なのですか? –

+0

これは必須条件ではありません。私はちょうど偽の概念実証の状況を作り出しています。私はタイムアウトなどをしていた可能性があります – Skyler

答えて

2

あなたはちょうどあなたがthen()に渡された関数の中で好きな値を返すことができますが、then()とないオリジナルpromiseによって返された新しい約束を返却する必要があります。

function getAndChangeValue() { 
    return getValue().then(function(arg) { 
     return "Bye"; 
    } 
} 
+0

それを変更する唯一の方法は、新しいDeferredオブジェクトを作成することです? (私はしないことを望んでいた - 私は同じ約束を再使用しないことがアンチパターンだと思った) – Skyler

+0

nm、今、それを得る、ありがとう! – Skyler

関連する問題