fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok'); // 检查响应状态
}
return response.json(); // 将响应解析为 JSON
})
.then(data => {
console.log(data); // 处理获取的数据
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error); // 处理错误
});
promise对象的链式处理:
html文件中添加div标签,
在js代码域中:
javascript复制代码
function loadImageAsync(url) {
var promise = new Promise(function (resolve, reject) {
const image = new Image();
image.onload = function () {
resolve(image);
};
image.onerror = function () {
reject(new Error('Couldnot load image at ' + url));
};
image.src = url;
});
return promise;
}
loadImageAsync("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png")
.then(function (res) {
console.log(res);
$("div").append(data)
}, function (error) {
$("div").html(error)
})