[問題] 同步變數接異步函數返回值
雖然這個問題有點蠢, 但是爬過相關文章都看不太懂. 目前是看到利用Promise
來解決, 但是找到的例子有點複雜不太能消化. 想請求大神幫忙.
舉個最簡單的例子 我今天想要做這樣的事情:
var x = getValue();
function getValue(){
var temp;
setTimeout(function(){temp = 3}, 2000);
return temp
}
這時候因為執行返回時 temp 還沒有被賦值, 所以x 會是undefined.
我該怎麼用promise 來讓我確定拿到我要得值才返回給 x 接住呢.
或者有其他技術可以實現. 不好意思, 初學js. 請指點迷津, 謝謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 75.109.208.14
※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1489269278.A.6D9.html
→
03/12 07:00, , 1F
03/12 07:00, 1F
→
03/12 07:00, , 2F
03/12 07:00, 2F
→
03/12 07:00, , 3F
03/12 07:00, 3F
→
03/12 07:26, , 4F
03/12 07:26, 4F
→
03/12 07:27, , 5F
03/12 07:27, 5F
→
03/12 07:28, , 6F
03/12 07:28, 6F
→
03/12 07:28, , 7F
03/12 07:28, 7F
→
03/12 07:29, , 8F
03/12 07:29, 8F
→
03/12 07:29, , 9F
03/12 07:29, 9F
推
03/12 11:43, , 10F
03/12 11:43, 10F
→
03/12 11:44, , 11F
03/12 11:44, 11F
→
03/12 11:45, , 12F
03/12 11:45, 12F
→
03/12 11:45, , 13F
03/12 11:45, 13F
推
03/12 11:47, , 14F
03/12 11:47, 14F
→
03/12 11:47, , 15F
03/12 11:47, 15F
→
03/12 12:21, , 16F
03/12 12:21, 16F
→
03/12 12:22, , 17F
03/12 12:22, 17F
→
03/12 12:22, , 18F
03/12 12:22, 18F
→
03/12 12:24, , 19F
03/12 12:24, 19F
→
03/12 12:25, , 20F
03/12 12:25, 20F
→
03/12 14:54, , 21F
03/12 14:54, 21F
→
03/12 14:54, , 22F
03/12 14:54, 22F
→
03/12 14:55, , 23F
03/12 14:55, 23F
→
03/12 14:56, , 24F
03/12 14:56, 24F
→
03/12 16:02, , 25F
03/12 16:02, 25F
→
03/12 16:02, , 26F
03/12 16:02, 26F
→
03/28 18:40, , 27F
03/28 18:40, 27F
Ajax 近期熱門文章
PTT數位生活區 即時熱門文章