javascript - promise應(yīng)用問題
問題描述
function loadImageAsync(url) { return new Promise(function(resolve, reject) { var image = new Image(); image.onload = function() { resolve(image); }; image.onerror = function() { reject(new Error(’Could not load image at ’ + url)); }; image.src = url; });}
想知道的是這個(gè)方法怎么用呢?我輸入了URL,然后再then里獲取對象image?可是我測了,沒有反應(yīng)!
問題解答
回答1:loadImageAsync(’./img/news-1.png’).then((img) => { document.getElementById('app').appendChild(img) console.log(img)})
這么調(diào)用,在then的參數(shù)就是resolve的參數(shù), 也就是image對象,把這個(gè)對象append到p上就可以實(shí)現(xiàn)功能
這是最終結(jié)果

loadImageAsync(url).then(function(img) { doSomething(); }).catch(function(err) { handleError(err); });回答3:
可以的 ,我在瀏覽器里試過了:
function loadImageAsync(url) { return new Promise(function(resolve, reject) { var image = new Image(); image.onload = function() { resolve(image); }; image.onerror = function() { reject(new Error(’Could not load image at ’ + url)); }; image.src = url; });}loadImageAsync(’https://www.baidu.com/img/bd_logo1.png’).then(function(){alert('jiazai wancheng')})
相關(guān)文章:
1. javascript - sublime快鍵鍵問題2. javascript - immutable配合react提升性能?3. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化4. 配置Apache時(shí),添加對PHP的支持時(shí)語法錯(cuò)誤5. css - 寫頁面遇到個(gè)布局問題,求大佬們幫解答,在線等,急!~6. javascript - nodejs關(guān)于進(jìn)程間發(fā)送句柄的一點(diǎn)疑問7. javascript - 移動端上不能實(shí)現(xiàn)拖拽布局嗎?8. phpstudy8.1支持win11系統(tǒng)嗎?9. 實(shí)現(xiàn)bing搜索工具urlAPI提交10. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務(wù)器還是不能訪問?

網(wǎng)公網(wǎng)安備