JavaScript Promise
new Promise( /* executor */ function(resolve, reject) { ... } );
- feature for asynchronous code
resolve
, reject
callback
Single return
- resolve๋ ํ๋์ ๊ฐ์ฒด๋ง ๋ฆฌํด
then()
, catch()
๋ก ์ด์ด์ ์คํ
function testFunction() {
return new Promise(function (resolve, reject) {
resolve("test1", "test2");
});
}
function run() {
testFunction()
.then(function (e) { console.log(arguments); })
.catch(function (err) { console.log(err); });
}
async function run() {
try {
var response = await testFunction();
console.log(response); // test1
} catch (err) {
console.log(err);
}
}
run();
Array destructuring
function testFunction() {
return new Promise(function(resolve, reject) {
resolve([ "test1", "test2"] );
});
}
async function run() {
const [firstRes, secondRes] = await testFunction();
console.log(firstRes, secondRes);
}
run();
ref