
getJSON, , JSON-. , JSON- done.const makeRequest = () =>
getJSON()
.then(data => {
console.log(data)
return "done"
})
makeRequest()const makeRequest = async () => {
console.log(await getJSON())
return "done"
}
makeRequest()async. await , async. , , , , return, done.await async-, .//
// await makeRequest()
// -
makeRequest().then((result) => {
// do something
})await getJSON() , console.log getJSON(), , ..then, , data, , , . , . , .try/catch. try/catch , JSON.parse, . .catch() . console.log .const makeRequest = () => {
try {
getJSON()
.then(result => {
// JSON
const data = JSON.parse(result)
console.log(data)
})
//
// .catch((err) => {
// console.log(err)
// })
} catch (err) {
console.log(err)
}catch , JSON.const makeRequest = async () => {
try {
// JSON
const data = JSON.parse(await getJSON())
console.log(data)
} catch (err) {
console.log(err)
}
}const makeRequest = () => {
return getJSON()
.then(data => {
if (data.needsAnotherRequest) {
return makeAnotherRequest(data)
.then(moreData => {
console.log(moreData)
return moreData
})
} else {
console.log(data)
return data
}
})
}const makeRequest = async () => {
const data = await getJSON()
if (data.needsAnotherRequest) {
const moreData = await makeAnotherRequest(data);
console.log(moreData)
return moreData
} else {
console.log(data)
return data
}
}promise1, , , promise2, promise3. , .const makeRequest = () => {
return promise1()
.then(value1 => {
// do something
return promise2(value1)
.then(value2 => {
// do something
return promise3(value1, value2)
})
})
}promise3 value1, , , . value1 value2 Promise.all .const makeRequest = () => {
return promise1()
.then(value1 => {
// do something
return Promise.all([value1, promise2(value1)])
})
.then(([value1, value2]) => {
// do something
return promise3(value1, value2)
})
}value1 value2 , .const makeRequest = async () => {
const value1 = await promise1()
const value2 = await promise2(value1)
return promise3(value1, value2)
}const makeRequest = () => {
return callAPromise()
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => {
throw new Error("oops");
})
}
makeRequest()
.catch(err => {
console.log(err);
//
// Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)callAPromise, (, , — , , ).const makeRequest = async () => {
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
throw new Error("oops");
}
makeRequest()
.catch(err => {
console.log(err);
//
// Error: oops at makeRequest (index.js:7:9)
})makeRequest, , , — then, then, - then…
.then « » (step-over), .then, «» .await , .
.then, , async/await. , , C# , , , , .Source: https://habr.com/ru/post/326074/
All Articles